package cn.darven.ui;

import cn.darven.db.SQLServerDB;
import cn.darven.xslt.XsltTransformer;

import javax.swing.*;

/**
 * @author darven
 * @date 2025/11/3
 * @description 数据库管理类
 */
public class DatabaseManager {
    private SQLServerDB sqlServerDB;
    private XsltTransformer xsltTransformer;
    private MainFrame mainFrame;

    public DatabaseManager(MainFrame mainFrame) {
        this.mainFrame = mainFrame;
    }

    public void connectToDatabase() {
        if (sqlServerDB != null){
            return;
        }
        System.out.println("开始连接数据库");
        sqlServerDB = new SQLServerDB();
        xsltTransformer = new XsltTransformer();
        System.out.println("数据库连接成功");
        mainFrame.updateStatus("数据库连接成功");
    }

    public void executeQuery(JTextArea textArea) {
        if (sqlServerDB == null) {
            JOptionPane.showMessageDialog(mainFrame, "请先连接数据库");
            mainFrame.updateStatus("请先连接数据库");
            return;
        }
        mainFrame.updateStatus("正在执行查询");
        String s = sqlServerDB.fetchXmlData();
        textArea.setText(xsltTransformer.formatXml(s));
        mainFrame.updateStatus("查询完成");
    }

    public SQLServerDB getSqlServerDB() {
        return sqlServerDB;
    }

    public XsltTransformer getXsltTransformer() {
        return xsltTransformer;
    }
}